﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.TR.Bussiness;
using ZX.TR.Library;
using ZX.EHR.Library;
using DevExpress.Charts;
using DevExpress.XtraCharts;
using DevExpress.XtraCharts.Web;
using System.Data;
using ZX.Web.UI.Controls;
using System.Text;

namespace ZX.TR.Web
{
    public partial class QuestionnaireStatistics : BasePage
    {
        string questionnaireID = "";
        BTrQuestionnaireSubject bTrQuestionnaireSubject = new BTrQuestionnaireSubject();
        V_TrQuestionnaire v_TrQuestionnaire = new V_TrQuestionnaire();
        public string questionnaireName = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                questionnaireID = this.Request.QueryString["id"];
                if (questionnaireID != "")
                {
                    v_TrQuestionnaire = bTrQuestionnaireSubject.GetAllQuestionnaireInfoById(new Guid(questionnaireID));
                    if (v_TrQuestionnaire != null)
                    {
                        lblQname.Text = v_TrQuestionnaire.QuestionnaireName;
                        questionnaireName = v_TrQuestionnaire.QuestionnaireName;
                        lblQtype.Text = v_TrQuestionnaire.DeptName;
                        lbltotalPeopleNum.Text = bTrQuestionnaireSubject.GetAnswerQuestionnaireTotalPeopleNum(questionnaireID).ToString();
                        lblEffectivetotalPeopleNum.Text = bTrQuestionnaireSubject.GetEffectiveTotalPeopleNum(questionnaireID).ToString();
                        Session["trquestion"] = v_TrQuestionnaire.TrQuestionnaireID;
                    }
                    bind(Session["trquestion"] == null ? Guid.NewGuid() : new Guid(Session["trquestion"].ToString()));
                }
            }
        }

        private void bind(Guid guid)
        {
            DatUser duser = Session["User"] as DatUser;
            string condcondition = " SubjectType in ('单选题','多选题')";
            condcondition = " 1=1";
            IList<V_TrExam> lstExam = bTrQuestionnaireSubject.GetExamListById(guid, condcondition);
            rptList.DataSource = lstExam;
            rptList.DataBind();
        }

        #region 题目初始化
        /// <summary>
        /// 控件绑定事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rptList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Label lblType = e.Item.FindControl("lblType") as Label;
            HiddenField subjectInfoID = e.Item.FindControl("TrSubjectInfoID") as HiddenField;
            WebChartControl charSubjectInfo = e.Item.FindControl("charSubjectInfo") as WebChartControl;
            HyperLink lnkOpen = e.Item.FindControl("lnkOpen") as HyperLink;
            Panel plselectQusetion = e.Item.FindControl("plselectQusetion") as Panel;
            Panel plpdt = e.Item.FindControl("plpdt") as Panel;
            Panel plEssayQuestionItem = e.Item.FindControl("plEssayQuestionItem") as Panel;
            if (lblType != null && lblType.Text == "填空题")
            {
                Repeater rptEssayQuestionItem = e.Item.FindControl("rptEssayQuestionItem") as Repeater;
                rptEssayQuestionItem.DataSource = bTrQuestionnaireSubject.GetEssayQuestion(questionnaireID, subjectInfoID.Value);
                rptEssayQuestionItem.DataBind();

                lnkOpen.Visible = true;
                lnkOpen.NavigateUrl = "EssayQuestion.aspx?&questionnaireID=" + questionnaireID + "&subjectInfoID=" + subjectInfoID.Value;
                plselectQusetion.Visible = false;
                plpdt.Visible = false;
                plEssayQuestionItem.Visible = false;
            }
            if (lblType != null && lblType.Text == "判断题")
            {
                plselectQusetion.Visible = false;
                plpdt.Visible = true;
                plEssayQuestionItem.Visible = false;
            }

            if (lblType != null && (lblType.Text == "单选题" || lblType.Text == "多选题"))
            {
                Repeater rpt = e.Item.FindControl("rptItem") as Repeater;
                if (subjectInfoID != null)
                {
                    //取得数据源
                    DataTable dt = bTrQuestionnaireSubject.GetAnswerQuestionnaire(questionnaireID, subjectInfoID.Value);
                    //生成图形
                    charSubjectInfo.Visible = true;
                    BindXtraChartsSeries(charSubjectInfo, dt);

                    //生成列表
                    //rpt.DataSource = bTrQuestionnaireSubject.GetSubjectInfoToItem(new Guid(subjectInfoID.Value));
                    rpt.DataSource = dt;
                    rpt.DataBind();

                    plselectQusetion.Visible = true;
                    plpdt.Visible = false;
                    plEssayQuestionItem.Visible = false;

                }
            }
        }

        #endregion

        #region 计算比例
        /// <summary>
        /// 比例
        /// </summary>
        /// <returns></returns>
        public string GetCountPercent(string subjectInfoID, string answer)
        {
            decimal totalPeopleNum = 0, totalItemPeopleNum = 0,percent=0;
            decimal.TryParse(lblEffectivetotalPeopleNum.Text, out totalPeopleNum);
            totalItemPeopleNum = bTrQuestionnaireSubject.GetAnswerJudgeTotalPeopleNum(questionnaireID, subjectInfoID, answer);
            if (totalPeopleNum > 0)
            {
                percent = Math.Round(totalItemPeopleNum / totalPeopleNum * 100, 2);
            }
            return percent.ToString() + "%";
        }

        /// <summary>
        /// 人数
        /// </summary>
        /// <returns></returns>
        public string GetCount(string subjectInfoID, string answer)
        {
            return bTrQuestionnaireSubject.GetAnswerJudgeTotalPeopleNum(questionnaireID, subjectInfoID, answer).ToString();
        }

        #endregion

        #region 题目答案图例
        /// <summary>
        /// 题目答案图例
        /// </summary>
        private void BindXtraChartsSeries(WebChartControl charSubjectInfo, DataTable dt)
        {
            //DataTable dt  = bTrQuestionnaireSubject.GetAnswerQuestionnaire(questionnaireID,subjectInfoID);
            Series series = new Series();
            series.Name = "series1";
            //LineSeriesView view1 = new LineSeriesView();
            SideBySideBarSeriesView view1 = new SideBySideBarSeriesView();
            series.View = view1;
            series.LegendText = "比例(%)";
            series.ArgumentDataMember = "ItemCode";
            series.ValueDataMembers[0] = "percent";
            series.DataSource = dt;
            charSubjectInfo.Series.Add(series);

            //series = new Series();
            //series.Name = "series2";
            //SideBySideBarSeriesView view2 = new SideBySideBarSeriesView();
            //series.View = view2;
            //series.LegendText = "小计";
            //series.ArgumentDataMember = "ItemCode";
            //series.ValueDataMembers[0] = "totalCount";
            //series.DataSource = dt;
            //charSubjectInfo.Series.Add(series);
        }
        #endregion

        #region 导出EXCEL
        protected void btnToExcel_Click(object sender, EventArgs e)
        {
            try
            {
                ExportToExcel(Value_hid.Value);
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("错误：" + ex.Message);
            }
        }

        public void ExportToExcel(string htmlString)
        {
            Response.Clear();
            Response.Buffer = true;

            string fileName = "导出";
            StringBuilder strb = new StringBuilder();
            //显示Excel中的网格线
            strb.Append("<html xmlns='http://www.w3.org/1999/xhtml' xmlns:x='urn:schemas-microsoft-com:office:excel'>");
            strb.Append("<head>");
            strb.Append("<style type='text/css'>");
            strb.Append("body");
            strb.Append("{");
            strb.Append("font-family: 宋体, Arial, Helvetica, sans-serif;");
            strb.Append("font-size: 12px;");
            strb.Append("color: #333333;");
            strb.Append("background-color: #FFFFFF;");
            strb.Append("}");
            strb.Append("<!--[if gte mso 9]><xml>");
            strb.Append("<x:ExcelWorkbook>");
            strb.Append("<x:ExcelWorksheets>");
            strb.Append("<x:ExcelWorksheet>");
            strb.Append("<x:Name>导出</x:Name>");
            strb.Append("<x:WorksheetOptions>");
            strb.Append("<x:Print>");
            strb.Append("<x:ValidPrinterInfo/>");
            strb.Append("</x:Print>");
            strb.Append("</x:WorksheetOptions>");
            strb.Append("</x:ExcelWorksheet>");
            strb.Append("</x:ExcelWorksheets>");
            strb.Append("</x:ExcelWorkbook>");
            strb.Append("</xml>");
            strb.Append("<![endif]--> ");
            strb.Append("</head>");
            strb.Append("<body>");
            //添加页面内容
            strb.Append(htmlString);
            strb.Append("</body></html>");
            Response.AppendHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName + "", System.Text.Encoding.UTF8) + ".xls");
            Response.Charset = "GB2312";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.ContentType = "application/vnd.ms-excel";
            Response.Charset = string.Empty;
            Response.Write(strb);
            Response.End();
        }
        #endregion
    }

    public class ListComparer : IEqualityComparer<string>
    {
        public bool Equals(string a, string b)
        {
            if (a == b)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public int GetHashCode(string obj)
        {
            return 0;
        }
    }
}